<script lang="ts" setup>
import { onMounted, ref, computed, reactive } from 'vue';
import { useCourseStore } from '@/stores/course';
import type { courseForm, chapterForm, submissionForm } from '@/api/type'
import { getChapter, getCourseFile, type commentForm, type courseFileForm } from '@/api/course';
import CourseComment from "@/views/StudentView/CourseComment.vue"
// 从路由拿
const props = defineProps(['cid']);
// 拿到课程信息
//从仓库拿到课程相关值
const courseInfo = useCourseStore().courseInfo;
const thisCourse = ref<courseForm>({});
const getTeacherName = async () => {
    for (let i = 0; i < courseInfo.length; i++) {
        if (courseInfo[i].cid == props.cid) {
            thisCourse.value = courseInfo[i];
            break;
        }
    }
    console.log("userID", thisCourse.value.userid);

    let res = await getUserName(thisCourse.value.userid as number);
    thisCourse.value.userName = res.data

}
// const activeName = ref('first')
const activeName = useCourseStore().activeName;
// 作业
import type { homeworkForm } from '@/api/type'
import { studentHomework, subHomework } from '@/api/homework'
import { useStudentStore } from '@/stores/student';
let allHomework = reactive<homeworkForm[]>([]);
// 得到作业信息
const getAllHomework = async () => {
    let result = await studentHomework(props.cid, useStudentStore().studentInfo.id);
    allHomework = result.data
    console.log("homework==", allHomework);
}
import { useRouter } from 'vue-router';
import { getUserName } from '@/api/user';
import { useTokenStore } from '@/stores/token';
import { ElMessage, ElMessageBox } from 'element-plus';
const handleHomework = (id: any) => {
    // 在这里处理点击作业标题的逻辑，可以访问到当前行的数据对象
};

// 计算当前日期
const currentDate = computed(() => new Date());

// 定义方法判断是否在截止日期之前
const isBeforeDueDate = (dueDate: any) => {
    return currentDate.value < new Date(dueDate);
};

// 定义上传文件的方法
// 处理上传成功事件
const submission = ref<submissionForm>({})
const homeworkId = ref<number>()
const handleUploadSuccess = (response: any, file: any) => {
    // 处理上传成功的逻辑，比如更新数据等
    submission.value.homeworkFile = response.data
    submitHomework();
};//image/jpg,image/jpeg,image/png
import type { UploadProps } from 'element-plus'
const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const allowedTypes = ['image/jpg', 'image/jpeg', 'image/png', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/pdf'];
    // 获取文件的 MIME 类型
    const fileType = rawFile.type;
    if (!allowedTypes.includes(fileType)) {
        ElMessage.error('请上传图片、Word 文档以及 PDF 文档')
        return false
    }
    return true
}
//关于章节
const allChapter = ref<chapterForm[]>([]);
const getAllchapter = async () => {
    let result = await getChapter(props.cid);
    allChapter.value = result.data;
}
//进入具体的章节信息
const router = useRouter();
const chapterDetail = (chapterId: number) => {
    console.log("chapterId", chapterId);

    router.replace({
        name: "chapter",
        query: {
            id: chapterId,
            cid: props.cid
        }
    });
}
const submitHomework = () => {
    ElMessageBox.confirm(`确认提交吗？`)
        .then(async () => {
            submission.value.submissionDate = new Date()
            submission.value.studentId = useStudentStore().studentInfo.id;
            submission.value.homeworkId = homeworkId.value;
            let result = await subHomework(submission.value)
            ElMessage.success(result.data)
            window.location.reload();
        })
        .catch(() => {
            console.error();
        })
}
// 资料下载
const studyFile = ref<courseFileForm[]>([])
const getStudyFile = async () => {
    let res = await getCourseFile(props.cid);
    studyFile.value = res.data
}
onMounted(() => {
    getTeacherName();
    getAllchapter();
    getAllHomework();
    getStudyFile();
})

</script>
<template>
    <div class="main">
        <el-image class="course-image" :src="thisCourse.courseImg" fit="contain"></el-image>
        <div class="details">
            <el-descriptions :title="thisCourse.courseName" :column="2" width="150px">
                <el-descriptions-item label="任课教师：">
                    {{ thisCourse.userName }}
                </el-descriptions-item>
                <el-descriptions-item></el-descriptions-item>
                <el-descriptions-item label=" 专业类别："> {{ thisCourse.major }}</el-descriptions-item>
                <el-descriptions-item label="班级：">{{ thisCourse.className }}</el-descriptions-item>
                <el-descriptions-item label="课程简介：">{{ thisCourse.introduction }}</el-descriptions-item>
            </el-descriptions>
        </div>

        <!-- 章节展示 -->
        <div class="chapter">
            <el-tabs v-model="activeName" class="demo-tabs">
                <el-collapse accordion>
                    <el-tab-pane label="章节" name="first">
                        <template v-for="item in allChapter" :key="item.id">
                            <el-collapse-item :name="item.id">
                                <template #title>
                                    <el-button size="small" style="margin-right: 10px;"
                                        @click="chapterDetail(item.id as number)">进入</el-button>
                                    <el-icon style="margin-right: 10px;">
                                        <Chicken />
                                    </el-icon>
                                    {{ item.name }}
                                </template>
                                {{ item.introduction }}
                            </el-collapse-item>
                        </template>
                    </el-tab-pane>
                    <el-tab-pane label="作业" name="second">
                        <el-table :data="allHomework" stripe style="width: 100%;" max-height="350">
                            <el-table-column prop="id" label="ID" width="80"></el-table-column>
                            <el-table-column label="作业标题">
                                <template v-slot="{ row }">
                                    <span @click="handleHomework(row.id)" style="cursor: pointer;">
                                        {{ row.title }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="dueDate" label="截止日期" width="180" />
                            <el-table-column label="创建人" width="140">
                                {{ thisCourse.userName }}
                            </el-table-column>
                            <el-table-column label="操作" width="120">
                                <template v-slot="{ row }">
                                    <el-upload v-show="isBeforeDueDate(row.dueDate)" action="/api/course/upload"
                                        :headers="{ Authorization: useTokenStore().token }" :limit="1"
                                        :on-success="handleUploadSuccess" :before-upload="beforeUpload">
                                        <el-button @click="homeworkId = row.id">提交</el-button>
                                    </el-upload>
                                    <el-button v-show="!isBeforeDueDate(row.dueDate)" disabled>已截止</el-button>
                                </template>
                            </el-table-column>
                            <el-table-column prop="submission.score" label="获得分数" width="180" />
                        </el-table>
                    </el-tab-pane>
                    <el-tab-pane label="课程留言" name="third">
                        <CourseComment :cid="cid"></CourseComment>
                    </el-tab-pane>
                    <el-tab-pane label="课程资源" name="four">
                        <el-table :data="studyFile" stripe style="width: 100%;" height="350">
                            <el-table-column label="序号" width="100">
                                <template v-slot="{ $index }">
                                    {{ $index + 1 }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="title" label="资料名称" width="200" />
                            <el-table-column prop="content" label="具体详情" />
                            <el-table-column label="学习资料" width="200">
                                <template v-slot="{ row }">
                                    <a :href="row.file" download>文件查看/下载</a>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-tab-pane>
                </el-collapse>
            </el-tabs>

        </div>
    </div>
</template>

<style scoped>
.main {
    display: flex;
    height: auto;
    margin-top: 20px;
    justify-content: center;
    flex-wrap: wrap;
    /* background: white; */
}

.course-image {
    margin-right: 20px;
    width: 200px;
    /* 根据需要调整图片宽度 */
}

.chapter {
    margin-top: 30px;
    width: 70%;
}

.details {
    margin-left: 60px;
    width: 600px;
    /* flex: 1; */
    /* background: yellowgreen; */
}

.introduction {
    margin-top: 20px;
}
</style>
